package com.loongtech.bi.support;

import com.loongtech.bi.entity.system.EntitySysUser;
import com.loongtech.bi.manager.system.SysUserManager;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * 权限控制拦截器
 * @author xckuang 
 * @date 2014-10-08
 */
@Service
public class PermissionFilter implements Filter {	
	private WebApplicationContext springContext = null;
	//这些页面不检查
	@SuppressWarnings("serial")
	private static Set<String> ignoreSet = new HashSet<String>() {
		{
			{
				add("pages/main.jsf");
                add("pages/mainPhone.jsf");
				add("pages/left.jsf");
				add("pages/right.jsf");
				add("pages/login.jsf");
                add("pages/system/cid.jsf");
                add("pages/serverOnlineNum.jsf");
			}
		}
	};
	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		Object userId = session.getAttribute("userId");
		String url = getLastPartURL(req.getRequestURI());
        // 集成部署和rest请求
        if (url.contains("cid.jsf") || url.contains("serverOnlineNum.jsf")) {
            fc.doFilter(request, response);
            return;
        }

        String username = request.getParameter("uname");
        String password = request.getParameter("sign");
        String time = request.getParameter("time");

        if (username != null) {
            session.setAttribute("redirectusername", username);
            session.setAttribute("redirectpassword", password);
            session.setAttribute("redirecttime", time);
        }

		if ("pages/login.jsf".equals(url)) {
			fc.doFilter(request, response);
			return;
		}
		if (userId == null) {
			((HttpServletResponse) response).sendRedirect("login.jsf");
			return;
		}
		if (ignoreSet.contains(url) || checkPermission((String) userId, url)) {
			fc.doFilter(request, response);
		} else {
			((HttpServletResponse) response).sendRedirect("login.jsf");
		}		
	}
	
	private String getLastPartURL(String url){
		if(null == url || url.isEmpty()){
			return url;
		}
		int index0 = url.lastIndexOf("/");
		int index1 = index0>0 ? url.substring(0,index0).lastIndexOf("/") : -1;
		return index1>0? url.substring(index1+1):url;
	}
	
	private boolean checkPermission(String username, String url){
		if(null == springContext){
			Log.bi.info("checkPermission springContext is null !");
			return false;
		}
		//判断参数
		if(null == username || username.isEmpty()){
			Log.bi.info("checkPermission username is null or empty !");
			return false;
		}
		if(null == url || url.isEmpty()){
			Log.bi.info("checkPermission url is null or empty !");
			return false;
		}
		
		//判断用户
		SysUserManager sysUserManager = (SysUserManager) springContext.getBean("systemUserManager");
		EntitySysUser user = sysUserManager.getBy(EntitySysUser.K.username,username);
		if(null == user){
			Log.bi.info("checkPermission user is null with name=" + username);
			return false;
		}
		//管理员直接返回
		if(user.getIsAdmin()){
			return true;
		}
		Object o = sysUserManager.getByQuery("select ur.roleId from EntitySysUserRole as ur, EntitySysRoleFunction as rf, EntitySysFunction as f where ur.roleId = rf.roleId and rf.functionId = f.id and ur.userId =? and f.src=?", user.getId(),url);
		return null != o;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		springContext = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext());
	}
}
